package gis.sqlbase;

import gis.common.GisConfig;
import gis.core.utils.XMLUtils;

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

public class DatabaseManage {

    private static Logger logger = LoggerFactory.getLogger(DatabaseManage.class);
    private static Map<String, ConnectionInfor> connectionConfig = new HashMap<String, ConnectionInfor>();
    private static Map<String, SQLHelper> dbs = new HashMap<String, SQLHelper>();

    /**
     * 获取数据访问实例
     *
     * @param databaseName
     * @return
     */
    public static SQLHelper Instance(DatabaseName databaseName) {
        return new DatabaseManage().GetDatabaseManage(databaseName);
    }

    /**
     * 创建数据访问实例
     *
     * @param databaseName
     * @return
     */
    public SQLHelper GetDatabaseManage(DatabaseName databaseName) {
        SQLHelper sqlHelper = null;
        try {
            if (connectionConfig.isEmpty()) {
                LoadConnectionConfigs();
            }
            String keyString = databaseName.name();
            if (!connectionConfig.containsKey(keyString)) {
                throw new Exception("无法查询到" + keyString + "连接字符串");
            }
            if (dbs.containsKey(keyString)) {
                sqlHelper = dbs.get(keyString);
            } else {
                sqlHelper = new SQLHelper(connectionConfig.get(keyString));
                dbs.put(keyString, sqlHelper);

            }
        } catch (Exception e) {
            logger.error("创建数据适配器出错:" + e.getMessage());
            e.printStackTrace();
        }

        return sqlHelper;
    }


    /**
     * 读取数据库配置信息
     *
     * @throws Exception
     */
    private void LoadConnectionConfigs() throws Exception {
        String area = GisConfig.GetInstance().getArea();
        //String pathString = this.getClass().getResource("/").getPath().replaceAll("target/classes/", "src/main/resources/gisconfig") + "/connection." + area + ".xml";

        Element element = XMLUtils.getInstance().loadXmlFileName("gisconfig/" + area + "/connection." + area + ".xml");

        NodeList list = element.getElementsByTagName("connection");
        if (list == null || list.getLength() == 0) {
            throw new Exception("无法读取数据库连接信息");
        }

        for (int i = 0; i < list.getLength(); i++) {
            Element node = (Element) list.item(i);
            if (node != null) {
                String keyString = node.getAttribute("name");
                if (connectionConfig.containsKey(keyString) == false) {

                    ConnectionInfor connectionInfor = new ConnectionInfor();
                    connectionInfor.setDriver(node.getAttribute("drive"));
                    connectionInfor.setUrl(node.getAttribute("url"));
                    connectionInfor.setUser(node.getAttribute("user"));
                    connectionInfor.setPassword(node.getAttribute("password"));
                    connectionConfig.put(keyString, connectionInfor);
                } else {
                    logger.info("读取连接字符串 时发现关键字在 " + keyString + " 重复，请确认！");
                }

            }
        }

    }

}
